use actix_web::{App, fs, http::{header, Method}, middleware::{self, cors::Cors}};
use common::db::init;
use common::state::AppState;
use controller::{api::user::{login, register}, frontend::{index, path}};
use std::cell::Cell;

pub fn api_state() -> App<AppState> {
    let addr = init();
    println!("{}", "addr start init");
    App::with_state(AppState { db: addr.clone() })
        .middleware(middleware::Logger::default())
        .middleware(middleware::Logger::new("%a %{User-Agent}i"))
        .prefix("/api")
        .configure(|app| Cors::for_app(app)
            .allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
            .allowed_headers(vec![header::ORIGIN, header::AUTHORIZATION, header::ACCEPT, header::CONTENT_TYPE])
            .supports_credentials()
            .max_age(3600)
            .resource("/register", |r| { r.method(Method::POST).with(register); })
            .resource("/login", |r| { r.method(Method::POST).with(login); })
            .register())
}

pub fn app() -> App {
    App::new()
        .middleware(middleware::Logger::default())
        .resource("/", |r| r.f(index))
        .resource("/a/{tail:.*}", |r| r.f(path))
        .handler("/", fs::StaticFiles::new("public/dist").unwrap())
}
